package com.mz.ozy.activity.me;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.mz.ozy.R;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.CarGoodsBean;
import com.mz.ozy.bean.CarGoodsDetailBean;
import com.mz.ozy.bean.QiNiuBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.ReturnPresenter;
import com.mz.ozy.mvp.view.RetunContract;
import com.mz.ozy.utils.BitmapUtils;
import com.mz.ozy.utils.QiNiuManger;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.ImageDialog;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zhihu.matisse.Matisse;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by Administrator on 2018/11/21.
 * 退换货详情
 */

public class ReturnGoodsDetailsActivity extends BaseActivity<RetunContract.View, ReturnPresenter> implements RetunContract.View {
    private static final int REQUEST_CODE_FEED = 24;

    @BindView(R.id.photoIv1)
    ImageView mPhotoIv1;
    @BindView(R.id.photoIv2)
    ImageView mPhotoIv2;
    @BindView(R.id.photoIv3)
    ImageView mPhotoIv3;

    @BindView(R.id.tv_invite)
    TextView tvInvite;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.numberTv)
    TextView numberTv;
    @BindView(R.id.tv_moey)
    TextView tvMoey;
    @BindView(R.id.et_version)
    EditText etVersion;
    private String img1 = "";
    private String img2 = "";
    private String img3 = "";
    private int tag = -1;
    private int tag1 = -1;
    private List<QiNiuBean> mPhotoList = new ArrayList<>();
    private String mPrice;
    private int num;
    private int curnum;
    private String id;
    private int type;
    private String url;
    private String marPrice;
    private int applyService = -1;
    private int state = -1;
    private String instructions;
    private int orderState;
    private int obType;

    public static void start(Context context, String price, String marPrice, String num, String id, int type, String url,
                             int applyService, int state, String img1, String img2, String img3, String instructions, int orderState, int obType) {
        Intent starter = new Intent(context, ReturnGoodsDetailsActivity.class);
        //starter.putExtra();
        starter.putExtra("price", price);
        starter.putExtra("marPrice", marPrice);
        starter.putExtra("num", num);
        starter.putExtra("id", id);
        starter.putExtra("type", type);
        starter.putExtra("url", url);
        starter.putExtra("applyService", applyService);
        starter.putExtra("state", state);
        starter.putExtra("img1", img1);
        starter.putExtra("img2", img2);
        starter.putExtra("img3", img3);
        starter.putExtra("instructions", instructions);
        starter.putExtra("orderState", orderState);
        starter.putExtra("obType", obType);

        context.startActivity(starter);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_goods_details);
        ButterKnife.bind(this);
        initTitle();
        mPrice = getIntent().getStringExtra("price");
        num = Integer.parseInt(getIntent().getStringExtra("num"));
        curnum = num;
        id = getIntent().getStringExtra("id");
        marPrice = getIntent().getStringExtra("marPrice");
        url = getIntent().getStringExtra("url");
        img1 = getIntent().getStringExtra("img1");
        img2 = getIntent().getStringExtra("img2");
        img3 = getIntent().getStringExtra("img3");
        instructions = getIntent().getStringExtra("instructions");
        applyService = getIntent().getIntExtra("applyService", -1);
        state = getIntent().getIntExtra("state", -1);
        orderState = getIntent().getIntExtra("orderState", -1);
        obType = getIntent().getIntExtra("obType", -1);
        tag = applyService;
        tag1 = state;
        tvCenterTitle.setText("退换货申请");
        type = getIntent().getIntExtra("type", 0);
        if (!TextUtils.isEmpty(instructions)) {
            etVersion.setText(instructions);
            etVersion.setSelection(instructions.length());
        }
        tvMoey.setText(getPrice());
        numberTv.setText(num + "");
        if (!TextUtils.isEmpty(img1)) {
            mPhotoIv1.setVisibility(View.VISIBLE);
            GlideUtils.loadRoundImg(this, mPhotoIv1, img1, R.mipmap.default_foods_icon, 4);
        }
        if (!TextUtils.isEmpty(img2)) {
            mPhotoIv2.setVisibility(View.VISIBLE);
            GlideUtils.loadRoundImg(this, mPhotoIv2, img2, R.mipmap.default_foods_icon, 4);
        }
        if (!TextUtils.isEmpty(img3)) {
            mPhotoIv3.setVisibility(View.VISIBLE);
            GlideUtils.loadRoundImg(this, mPhotoIv3, img3, R.mipmap.default_foods_icon, 4);
        }
        if (orderState == 1) {
            tag = 2;
            tvInvite.setText("仅退款");
            tvInvite.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        } else {
            if (applyService == 0) {
                tvInvite.setText("仅退款");
            } else if (applyService == 1) {
                tvInvite.setText("退货退款");
            } else if (applyService == 2) {
                tag = 2;
                tvInvite.setText("仅退款");
                tvInvite.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            }
        }
        switch (state) {
            case 0:
                tvVersion.setText("七天无理由退货");
                break;
            case 1:
                tvVersion.setText("质量问题");
                break;
            case 2:
                tvVersion.setText("商品描述不符");
                break;
            case 3:
                tvVersion.setText("生产日期/保质期描述不符");
                break;
            case 4:
                tvVersion.setText("商家发错货");
                break;
            case 5:
                tvVersion.setText("假冒品牌");
                break;
            case 6:
                tvVersion.setText("主商品破损");
                break;
            case 7:
                tvVersion.setText("其他");
                break;
        }
        //  mPresenter.onSDetail(this, id);
    }

    @NotNull
    private String getPrice() {
        String price = "";
        final double mTotalPrice = curnum * Double.valueOf(mPrice);
        final double mTotalMarketPrice = curnum * Double.valueOf(marPrice);
        if (mTotalPrice != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(mTotalPrice);
        }
        if (mTotalMarketPrice != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }

        if (obType == 1) {
            return price.replace("¥", "") + "欧花";
        }

        return price;
    }

    @OnClick({R.id.lessTv, R.id.addTv, R.id.rele_invite, R.id.rele_version, R.id.btn_confirm, R.id.uploadIv, R.id.photoIv1, R.id.photoIv2, R.id.photoIv3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.uploadIv:
                RxPermissions.getInstance(ReturnGoodsDetailsActivity.this)
                        .request(Manifest.permission.CAMERA)//这里填写所需要的权限
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                                    BitmapUtils.selectPhoto1(ReturnGoodsDetailsActivity.this, 3, REQUEST_CODE_FEED);
                                } else {
                                    Log.i("permissions", Manifest.permission.READ_EXTERNAL_STORAGE + "：" + "获取失败");
                                }
                            }
                        });
                break;
            case R.id.lessTv:
                if (curnum > 1) {
                    curnum--;
                    numberTv.setText(curnum + "");
                    tvMoey.setText(getPrice());
                } else {
                    ToastUtils.showToast("数量不能小于1");
                }
                break;
            case R.id.addTv:
                if (curnum < num) {
                    curnum++;
                    numberTv.setText(curnum + "");
                    tvMoey.setText(getPrice());
                }
                break;
            case R.id.photoIv1:
                if (mPhotoList.size() > 0) {
                    if (!TextUtils.isEmpty(mPhotoList.get(0).getUrl())) {
                        new ImageDialog(ReturnGoodsDetailsActivity.this, mPhotoList.get(0).getUrl()).builder().show();
                    }
                } else if (!TextUtils.isEmpty(img1)) {
                    new ImageDialog(ReturnGoodsDetailsActivity.this, img1).builder().show();
                }
                break;
            case R.id.photoIv2:
                if (mPhotoList.size() > 1) {
                    if (!TextUtils.isEmpty(mPhotoList.get(1).getUrl())) {
                        new ImageDialog(ReturnGoodsDetailsActivity.this, mPhotoList.get(1).getUrl()).builder().show();
                    }
                } else if (!TextUtils.isEmpty(img2)) {
                    new ImageDialog(ReturnGoodsDetailsActivity.this, img2).builder().show();
                }
                break;
            case R.id.photoIv3:
                if (mPhotoList.size() > 2) {
                    if (!TextUtils.isEmpty(mPhotoList.get(2).getUrl())) {
                        new ImageDialog(ReturnGoodsDetailsActivity.this, mPhotoList.get(2).getUrl()).builder().show();
                    }
                } else if (!TextUtils.isEmpty(img3)) {
                    new ImageDialog(ReturnGoodsDetailsActivity.this, img3).builder().show();
                }
                break;
            case R.id.rele_invite:
                if (orderState != 1 && applyService != 2) {
                    dialog();
                }
                break;
            case R.id.rele_version:
                dialog1();
                break;
            case R.id.btn_confirm:
                String invite = tvInvite.getText().toString();
                String version = tvVersion.getText().toString();
                String versionEt = etVersion.getText().toString();

                if (tag == 13) {
                    ToastUtils.showToast("请选择服务类型");
                    return;
                }
                if (tag1 == 13) {
                    ToastUtils.showToast("请选择退款原因");
                    return;
                }
                if (mPhotoList.size() > 0) {
                    mPresenter.onUpReturn(this, id, tag + "", tag1 + "", num + "", versionEt, mPhotoList, type, url);
                } else {
                    List<String> imgList = new ArrayList<>();
                    if (!TextUtils.isEmpty(img1)) {
                        final int lastindex = img1.lastIndexOf("/");
                        String imgKey = img1.substring(lastindex + 1);
                        imgList.add(imgKey);
                    }
                    if (!TextUtils.isEmpty(img2)) {
                        final int lastindex = img2.lastIndexOf("/");
                        String imgKey = img2.substring(lastindex + 1);
                        imgList.add(imgKey);
                    }
                    if (!TextUtils.isEmpty(img3)) {
                        final int lastindex = img3.lastIndexOf("/");
                        String imgKey = img3.substring(lastindex + 1);
                        imgList.add(imgKey);
                    }
                    mPresenter.onAppeal1(this, id, tag + "", tag1 + "", curnum + "", versionEt, imgList, type, url);
                }
                break;
        }
    }

    private void dialog() {
        Dialog bottomDialog = new Dialog(ReturnGoodsDetailsActivity.this, R.style.dialogtheme);
        View contentView = LayoutInflater.from(ReturnGoodsDetailsActivity.this).inflate(R.layout.dialog_sx, null);
        bottomDialog.setContentView(contentView);
        RadioButton radioButton1 = contentView.findViewById(R.id.btn_cancel);
        RadioButton radioButton2 = contentView.findViewById(R.id.bt);
        if (applyService == 0) {
            radioButton1.setChecked(true);
        } else if (applyService == 1) {
            radioButton2.setChecked(true);
        }
        Window window = bottomDialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

        RadioGroup payGroup1 = bottomDialog.findViewById(R.id.pay_group);
        if (SPUtils.getInstance(ReturnGoodsDetailsActivity.this).getInt("type1", 0) != 13) {
            payGroup1.check(SPUtils.getInstance(ReturnGoodsDetailsActivity.this).getInt("type1", 0));
        }
        bottomDialog.findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (tag == 0) {
                    tvInvite.setText("仅退款");
                } else {
                    tvInvite.setText("退货退款 ");
                }

                bottomDialog.cancel();
            }
        });


        payGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                View checkedView = group.findViewById(checkedId);
                tag = Integer.valueOf(checkedView.getTag().toString());
                SPUtils.getInstance(ReturnGoodsDetailsActivity.this).putInt("type1", checkedId);
            }
        });

        bottomDialog.show();
    }

    private void dialog1() {
        Dialog bottomDialog = new Dialog(ReturnGoodsDetailsActivity.this, R.style.dialogtheme);
        View contentView = LayoutInflater.from(ReturnGoodsDetailsActivity.this).inflate(R.layout.dialog_sx_one, null);
        bottomDialog.setContentView(contentView);
        RadioButton radioButton1 = contentView.findViewById(R.id.btn_cancel);
        RadioButton radioButton2 = contentView.findViewById(R.id.btn);
        RadioButton radioButton3 = contentView.findViewById(R.id.bt);
        RadioButton radioButton4 = contentView.findViewById(R.id.bto);
        RadioButton radioButton5 = contentView.findViewById(R.id.bto_one1);
        RadioButton radioButton6 = contentView.findViewById(R.id.bto_one2);
        RadioButton radioButton7 = contentView.findViewById(R.id.bto_one3);
        RadioButton radioButton8 = contentView.findViewById(R.id.bto_one4);
        switch (state) {
            case 0:
                radioButton1.setChecked(true);
                break;
            case 1:
                radioButton2.setChecked(true);
                break;
            case 2:
                radioButton3.setChecked(true);
                break;
            case 3:
                radioButton4.setChecked(true);
                break;
            case 4:
                radioButton5.setChecked(true);
                break;
            case 5:
                radioButton6.setChecked(true);
                break;
            case 6:
                radioButton7.setChecked(true);
                break;
            case 7:
                radioButton8.setChecked(true);
                break;
        }
        Window window = bottomDialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        RadioGroup payGroup1 = bottomDialog.findViewById(R.id.pay_group1);
        if (SPUtils.getInstance(ReturnGoodsDetailsActivity.this).getInt("type", 0) != 13) {
            payGroup1.check(SPUtils.getInstance(ReturnGoodsDetailsActivity.this).getInt("type", 0));
        }
        bottomDialog.findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (tag1) {
                    case 0:
                        tvVersion.setText("七天无理由退货");
                        break;
                    case 1:
                        tvVersion.setText("质量问题");
                        break;
                    case 2:
                        tvVersion.setText("商品描述不符");
                        break;
                    case 3:
                        tvVersion.setText("生产日期/保质期描述不符");
                        break;
                    case 4:
                        tvVersion.setText("商家发错货");
                        break;
                    case 5:
                        tvVersion.setText("假冒品牌");
                        break;
                    case 6:
                        tvVersion.setText("主商品破损");
                        break;
                    case 7:
                        tvVersion.setText("其他");
                        break;
                }

                bottomDialog.cancel();
            }
        });
        payGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                View checkedView = group.findViewById(checkedId);
                tag1 = Integer.valueOf(checkedView.getTag().toString());
                SPUtils.getInstance(ReturnGoodsDetailsActivity.this).putInt("type", checkedId);
            }
        });

        bottomDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtils.getInstance(ReturnGoodsDetailsActivity.this).putInt("type", 13);
        SPUtils.getInstance(ReturnGoodsDetailsActivity.this).putInt("type1", 13);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            GlideUtils.loadRoundImg(this, mPhotoIv1, "", R.mipmap.default_foods_icon, 4);
            GlideUtils.loadRoundImg(this, mPhotoIv2, "", R.mipmap.default_foods_icon, 4);
            GlideUtils.loadRoundImg(this, mPhotoIv3, "", R.mipmap.default_foods_icon, 4);
            List<Uri> list = Matisse.obtainResult(data);
            try {
                mPhotoList.clear();
                for (int i = 0; i < list.size(); i++) {
                    InputStream inputStream = getContentResolver().openInputStream(list.get(i));
                    Bitmap bitmap = BitmapUtils.inputstremToBitmap(inputStream, 2);
                    if (bitmap != null) {
                        String keyName = QiNiuManger.getInstance().getKeyName() + i;  //图片名
                        //压缩后图片路径不能为空，可能保存出错
                        String cPath = BitmapUtils.saveImageSdcard(bitmap, keyName);
                        mPhotoList.add(new QiNiuBean(keyName, cPath));
                        if (i == 0) {
                            mPhotoIv1.setVisibility(View.VISIBLE);
                            GlideUtils.loadRoundImg(this, mPhotoIv1, cPath, R.mipmap.default_foods_icon, 4);
                        } else if (i == 1) {
                            mPhotoIv2.setVisibility(View.VISIBLE);
                            GlideUtils.loadRoundImg(this, mPhotoIv2, cPath, R.mipmap.default_foods_icon, 4);
                        } else if (i == 2) {
                            mPhotoIv3.setVisibility(View.VISIBLE);
                            GlideUtils.loadRoundImg(this, mPhotoIv3, cPath, R.mipmap.default_foods_icon, 4);
                        }
                    }
                    assert bitmap != null;
                    bitmap.recycle();
                    bitmap = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onCanclInvite(JSONObject s) {

    }

    @Override
    public void onJh(JSONObject s) {

    }

    @Override
    public void onUpReturn(JSONObject s) {
        finish();
        SPUtils.getInstance(ReturnGoodsDetailsActivity.this).putInt("type", 13);
        SPUtils.getInstance(ReturnGoodsDetailsActivity.this).putInt("type1", 13);
//        ReturnGoodsListActivity.start(this);
        ToastUtils.showToast("申请成功");
    }

    @Override
    public void onlist(CarGoodsBean s) {

    }

    @Override
    public void onlistDetail(CarGoodsDetailBean s) {

    }

    @Override
    public void onShDetail(CarGoodsDetailBean s) {

    }
}

